package com.example.cangzhou.utils;

import cn.hutool.core.io.FileUtil;
import com.example.cangzhou.entity.Resource;
import com.example.cangzhou.service.ResourceService;
import com.example.cangzhou.vo.FileVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.List;

@Slf4j
@Component
public class LocalUtil{

    @Value("${local.uploadUrl}")
    private String uploadUrl;

    @Value("${local.downloadUrl}")
    private String downloadUrl;

    @Autowired
    private ResourceService resourceService;

    public void deleteFile(List<String> files) {
        if (CollectionUtils.isEmpty(files)) {
            return;
        }

        for (String filePath : files) {
            File file = new File(filePath.replace(downloadUrl, uploadUrl));
            if (file.exists() && file.isFile()) {
                if (file.delete()) {
                    log.info("文件删除成功：" + filePath);
                    resourceService.lambdaUpdate().eq(Resource::getPath, filePath).remove();
                } else {
                    log.error("文件删除失败：" + filePath);
                }
            } else {
                log.error("文件不存在或者不是一个文件：" + filePath);
            }
        }
    }

    public FileVO saveFile(FileVO fileVO) {
        String path = fileVO.getRelativePath();
        String absolutePath = uploadUrl + path + fileVO.getStoreType();
        if (FileUtil.exist(absolutePath)) {
            throw new RuntimeException("文件已存在！");
        }
        try {
            File newFile = FileUtil.touch(absolutePath);
            fileVO.getFile().transferTo(newFile); //
            FileVO result = new FileVO();
            result.setAbsolutePath(absolutePath);
            result.setVisitPath(downloadUrl + path);
            return result;
        } catch (IOException e) {
            log.error("文件上传失败：", e);
            FileUtil.del(absolutePath);
            throw new RuntimeException("文件上传失败！");
        }
    }
}
